package;
import fl.controls.Button;
import fl.controls.List;
import fl.controls.TextArea;
import fl.controls.TextInput;
import fl.data.DataProvider;

import flash.Lib;
import flash.display.MovieClip;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.NetStatusEvent;
import flash.net.NetConnection;
import flash.net.Responder;

class Main extends MovieClip
{
	static var app:String='/chat';
	static var path:String;
	var nc:NetConnection;
	var btn:Button;
	var login:Login;
	var chat:Chat;
	
	public static function main()
	{
		Lib.current.addChild(new Main());
	}
	public function new()
	{
		super();
		
		nc = new NetConnection();
		nc.client=this;
		nc.objectEncoding = 0;
		nc.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
		
		btn = new Button();
		btn.label="Connect";
		btn.addEventListener(MouseEvent.CLICK, onBtnClick);
		addChild(btn);
		
		positionMiddle(btn);
		addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
	}
	function onBtnClick(event:MouseEvent):Void
	{
		nc.connect(path);//nc.connect(path, {name:"jan"});
	}
	function onNetStatus(event:NetStatusEvent):Void
	{
		trace("code:" + event.info.code);
		trace("description:" + event.info.description);
		if(event.info.code =='NetConnection.Connect.Success')
		{
			removeChild(btn);
			login = new Login(nc);
			login.addEventListener("login", onLogin);
			addChild(login);
			positionMiddle(login);
		}
	}
	function onLogin(event:Event):Void
	{
		login.removeEventListener("login", onLogin);
		removeChild(login);
		
		chat = new Chat(nc, login.getUserName());
		addChild(chat);
		positionMiddle(chat);
	}
	function onAddedToStage(event:Event):Void
	{
		removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		stage.scaleMode=StageScaleMode.NO_SCALE;
		stage.align=StageAlign.TOP_LEFT;
		stage.addEventListener(Event.RESIZE, onStageResize); 
		path = "rtmp://"+getUri();
	}
	function onStageResize(event:Event):Void
	{
		if(btn!=null && btn.parent!=null)
			positionMiddle(btn);
		if(login!=null && login.parent!=null)
			positionMiddle(login);
		if(chat!=null && chat.parent!=null)
		{
			positionMiddle(chat);
			if(chat.x <0)
				chat.x=0;
			if(chat.y <0)
				chat.y=0;
		}
	}
	function positionMiddle(obj:flash.display.DisplayObject)
	{
		obj.x = (Lib.current.stage.stageWidth-obj.width)/2;
		obj.y = (Lib.current.stage.stageHeight-obj.height)/2;
	}
	function getUri():String
	{
		var parameters:Dynamic = flash.Lib.current.loaderInfo.parameters;
		//trace(parameters);
		var u = Reflect.field(parameters, "uri");
		if(u!=null)
			return u;
		var h = Reflect.field(parameters, "host");
		var p = Reflect.field(parameters, "port");
		var a = Reflect.field(parameters, "app");
		return (h==null?"localhost":h) + (p==null?":1935":":"+p) + (a==null?app:a);
	}
}